from docx import Document
from docx.oxml.table import CT_Tbl
from docx.oxml.text.paragraph import CT_P
from docx.table import Table
import os

class WordTableLine2solidController:
    def __init__(self, view):
        self.view = view

    def handle_button_click(self):
        self.view.show_message("Sub Window clicked!")

    def extract_table_data(self, table):
        """提取表格数据"""
        data = []
        for row in table.rows:
            row_data = [cell.text for cell in row.cells]
            data.append(row_data)
        return data

    def create_default_table(self, doc, data, previous_paragraph):
        """在指定段落后创建一个新的默认样式表格"""
        # 创建一个新的表格
        table = doc.add_table(rows=len(data), cols=len(data[0]), style='Table Grid')

        # 填充表格数据
        for i, row in enumerate(table.rows):
            for j, cell in enumerate(row.cells):
                # 设置单元格内容
                cell.text = data[i][j]

                # 获取单元格中的段落
                for paragraph in cell.paragraphs:
                    # 设置段落中的所有文本的字体和字号
                    for run in paragraph.runs:
                        run.font.name = '宋体'
                        # run.font.size = Pt(10.5)  # 五号字对应大约10.5磅

        # 将新表格插入到原位置
        new_table_element = table._element
        previous_paragraph.addnext(new_table_element)

        # 返回新表格对象
        return table

    def reset_tables(self, doc_path, output_word_path):
        # 打开文档
        doc = Document(doc_path)

        # 存储需要删除的表格及其前一个段落
        tables_to_reset = []
        for element in doc.element.body:
            if isinstance(element, CT_Tbl):
                # 获取表格前面的段落
                previous_paragraph = element.getprevious()
                while previous_paragraph is not None and not isinstance(previous_paragraph, CT_P):
                    previous_paragraph = previous_paragraph.getprevious()
                if previous_paragraph is None:
                    previous_paragraph = doc.add_paragraph()  # 如果没有前一个段落，添加一个空段落
                tables_to_reset.append((element, previous_paragraph))

        # 处理每个表格
        for table_element, previous_paragraph in tables_to_reset:
            # 创建 Table 对象
            table = Table(table_element, doc)

            # 提取表格数据
            data = self.extract_table_data(table)

            # 创建新的默认样式表格
            self.create_default_table(doc, data, previous_paragraph)

            # 删除旧的表格
            table_element.getparent().remove(table_element)

        # 保存修改后的文档
        doc.save(output_word_path)

    def table2default(self, document_path):
        # 输出Word文档的路径
        output_word_path = '默认表格样式'
        base_name = output_word_path
        extension = '.docx'

        i = 1
        while os.path.exists(f"{output_word_path}{extension}"):
            output_word_path = f"{base_name}({i})"
            i += 1

        output_word_path += extension

        self.reset_tables(document_path, output_word_path)

        return output_word_path